<template>
  <div class="entryFrom">
    <el-form style="margin: 0 auto" label-width="100px" class="demo-ruleForm">
      <el-row>
        <el-col>
          <el-form-item label="基本信息:">
            <div>
              <el-form
                label-position="right"
                :rules="rules"
                label-width="150px"
              >
                <el-form-item prop="sfzImage" class="img">
                  <img
                    v-if="sfzImage == null"
                    src="../../../public/img/carid.png"
                    height="100px"
                    width="100px"
                  />
                  <img v-else :src="sfzImage" height="100px" width="100px" />
                </el-form-item>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="姓名:" prop="name">
                      <el-input
                        clearable
                        v-model="username"
                        placeholder="请输入姓名"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="身份证号码:" prop="phone">
                      <el-input
                        v-model="user_code"
                        clearable
                        placeholder="请输入身份证号码"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="民族:" prop="phone">
                      <el-input
                        v-model="minzu"
                        clearable
                        placeholder="请输入民族"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="出生日期:" prop="work">
                      <div class="block">
                        <el-date-picker
                          @change="changedatetime($event)"
                          v-model="value1"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="选择日期"
                        >
                        </el-date-picker>
                      </div>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="年龄:" prop="age">
                      <el-input
                        v-model="age"
                        clearable
                        placeholder="请输入年龄"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="手机号码:" prop="phone">
                      <el-input
                        v-model="mobile"
                        clearable
                        placeholder="请输入婚姻状况"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="文化程度:" prop="culture">
                      <el-input
                        v-model="learn_level"
                        clearable
                        placeholder="请输入文化程度"
                      ></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item
                      label="婚姻状况:"
                      prop="marriage"
                      class="radio"
                    >
                      <el-radio v-model="radio1" label="1" @change="getValue()"
                        >已婚</el-radio
                      >
                      <el-radio v-model="radio1" label="2" @change="getValue()"
                        >未婚</el-radio
                      >
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row>
                  <el-col :span="12">
                    <el-form-item label="性别:" class="radio">
                      <el-radio v-model="radio3" label="1" @change="getValue()"
                        >男</el-radio
                      >
                      <el-radio v-model="radio3" label="2" @change="getValue()"
                        >女</el-radio
                      >
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="就业信息:" prop="work" class="radio">
                      <el-radio v-model="radio2" label="1" @change="getValue()"
                        >未就业</el-radio>
                      <el-radio v-model="radio2" label="2" @change="getValue()"
                        >已就业</el-radio>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="就业意向:" prop="work">
                      <el-input
                        v-model="job_to"
                        clearable
                        placeholder="请输入就业意向"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="半身照:" prop="work">
                      <el-upload
                        class="avatar-uploader"
                        action="http://px.0123china.cn/api/v1.upload/up"
                        :multiple="false"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="aaaa" style="width:104px;height:104px" :src="aaaa" class="avatar" />
                        <i v-else style="width:100px;height:100px;line-height:100px;background:#e6e6e6" class="el-icon-plus avatar-uploader-icon"></i>
                      </el-upload>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="身份证复印件:" prop="fujinImg">
                      <img
                        v-if="fujinImg == null"
                        src="../../../public/img/fuyin.png"
                        class="abcimg"
                      />
                      <img v-else :src="fujinImg" height="440px" width="340px" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <!-- 读卡器操作 -->
              <el-row :gutter="20" class="mb8" style="width: 100%">
                <el-col :span="8" style="text-align: right">
                  <el-button
                    type="success"
                    icon="el-icon-plus"
                    size="mini"
                    @click="connect"
                    >连接</el-button
                  >
                </el-col>
                <el-col :span="8">
                  <el-button
                    type="warning"
                    icon="el-icon-download"
                    size="mini"
                    @click="readCert"
                    >读卡</el-button
                  >
                </el-col>
                <el-col :span="8" style="text-align: left">
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    @click="disconnect"
                    >断开</el-button
                  >
                </el-col>
              </el-row>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item class="mb8">
        <el-button type="primary" @click="submitForm">添加学员</el-button>
        <el-button type="warning" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { Tag } from "element-ui";
import IdCard from "../../utils/idcard";
import axios from "axios"
export default {
  components: {},
  data() {
    return {
      value1: "", //出生日期时间控件
      //拍照
      videoWidth: 150,
      videoHeight: 150,
      imgSrc: "",
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      radio1: "",
      radio2: "",
      radio3: "",

      username: "",
      user_code: "",
      minzu: "",
      age: "",
      sex: "",
      card_img: "",
      birth: "",
      mer_status: "",
      mobile: "",
      learn_level: "",
      job_status: "",
      job_to: "",

      // 对话框的显隐
      showDialog: false,
      CertCtl: "",
      sfzImage: null, // 身份证照片
      // 查询参数
      IDCardForm: {
        name: "", // 姓名
        idCardNumber: "", // 身份证号码
        nation: "", // 民族
        birthday: "", // 出生日期
      },
      // 表单参数
      rules: {},
      timer: "",
      value: "",
      sTime: "",
      sfzpic: "",
      picc:"",
      avatarimg:"",
      aaaa:'',
      halfImg:'',
      userImg:'',
      fujinImg:null,
      fuyingImg:''
    };
  },
  created() {},
  methods: {
    beforeAvatarUpload(file) {
      //上传前的函数
      //上传前对图片类型和大小进行判断
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res, file) {
      // this.pic = res.pic//上传图片接口
      this.aaaa = "http://px.0123china.cn"+res.pic
      this.halfImg = res.pic
      console.log(this.aaaa);
      console.log("res",res);
      console.log("file",file);
      this.picc = URL.createObjectURL(file.raw);
      console.log("this.picc",this.picc);
    },
    handleAvatarSuccessaa(res, file) {
      this.pic = res.pic//上传图片接口
      this.avatarimg = "http://px.0123china.cn"+res.pic
      this.userImg = res.pic
      console.log("res",res);
      console.log("file",file);
      this.picc = URL.createObjectURL(file.raw);
      console.log("this.picc",this.picc);
    },
    //连接操作
    async connect() {
      let res = await IdCard.startConnect();
      if (res.resultFlag == 0) {
        this.$notify({
          title: "成功",
          message: res.errorMsg,
          type: "success",
        });
      }
    },
    //读卡操作
    async readCert() {
      let res = await IdCard.readCert();
      this.fujinImg = res.resultContent.identityPrintPic
      this.sfzImage = res.resultContent.identityPrintPic
      console.log("ressss",res);
      let codeid = res.resultContent.certNumber
      if (res.resultFlag == 0) {
        let a = await this.$api.home.checkArchive({
          user_code: codeid,
        });
        let is = a.data;
        console.log("is", is);
        if (is.code == 403) {
          this.$confirm("不在档案库中，是否录入?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              this.$message({
                type: "success",
                message: "确定录入",
              });
              
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消录入",
              });
              this.sfzImage = "";
              this.fujinImg = "",
              this.username = "";
              this.user_code = "";
              this.minzu = "";
              this.value1 = "";
              this.radio3 = "";
            });
      }
      if (res.resultFlag == 0) {
        this.$notify({
          title: "成功",
          message: res.errorMsg,
          type: "success",
        });
        
        }
        let messagea = res.resultContent;
        this.username = messagea.partyName;
        this.user_code = messagea.certNumber;
        this.minzu = messagea.nation;
        this.value1 = messagea.bornDay.replace(/(.{4})(.{2})/, "$1-$2-");
        if (messagea.gender == 0) {
          this.radio3 = "2";
        } else {
          this.radio3 = "1";
        }
        let getage = await this.$api.home.traineeAge({
          birthday :this.value1
        })
        this.age = getage.data.data
        console.log("getage",getage);
        this.sfzImage = "data:image/png;base64," + messagea.identityPic;
        this.fujinImg = "data:image/png;base64," + messagea.identityPrintPic;
        // base64编码的图片
        var base64Img = "data:image/png;base64," + messagea.identityPic;
      } else {
        this.$notify.error({
          title: "错误",
          message: res.errorMsg,
        });
      }
    },
    //断开连接
    async disconnect() {
      let res = await IdCard.disconnect();
      if (res.resultFlag == 0) {
        this.$notify({
          title: "成功",
          message: res.errorMsg,
          type: "success",
        });
      } else {
        this.$notify.error({
          title: "错误",
          message: res.errorMsg,
        });
      }
    },
    changedatetime(val) {
      this.sTime = val;
    },
    getValue() {
      this.sex = this.radio3;
      this.mer_status = this.radio1;
      this.job_status = this.radio2;
    },
    //添加学员
    async submitForm() {
      // this.dealImage(this.fujinImg,340,this.fujinImg)
      // console.log(this.dealImage);
      console.log("this.fujinImg",this.fujinImg);
      let bsUp = (
        await this.$api.home.aaaaaaaa({
          aaa: this.sfzImage,
        })
      ).data;
      console.log(bsUp);
      // console.log("this.sfzImage",this.sfzImage);
      console.log("this.fujinImg",this.fujinImg);
      // let fuying = (
      //   await this.$api.home.baseUpload({
      //     base64_img: this.fujinImg,
      //   })
      // ).data;
      
      // console.log("fuying",fuying);
      // this.sfzpic = bsUp.pic;
      // console.log(this.sfzpic);
      // this.fuyingImg = fuying.pic;
      // let add = (
      //   await this.$api.home.traineeAdd({
      //     username: this.username,
      //     user_code: this.user_code,
      //     minzu: this.minzu,
      //     age: this.age,
      //     sex: this.sex,
      //     birth: this.value1,
      //     mer_status: this.mer_status,
      //     mobile: this.mobile,
      //     learn_level: this.learn_level,
      //     job_status: this.job_status,
      //     job_to: this.job_to,
      //     card_img: this.sfzpic,
      //     half_img: this.halfImg,
      //     user_code_img:this.fuyingImg,
      //   })
      // ).data;
      // if (add.code == 200) {
      //   this.$notify({
      //     title: "成功",
      //     message: add.msg,
      //     type: "success",
      //   });
      // } else {
      //   this.$notify.error({
      //     title: "错误",
      //     message: add.msg,
      //   });
      // }
    },
    dealImage(base64, w, callback) {
                var newImage = new Image();
                var quality = 0.6;    //压缩系数0-1之间
                newImage.src = base64;
                newImage.setAttribute("crossOrigin", 'Anonymous');	//url为外域时需要
                var imgWidth, imgHeight;
                newImage.onload = function () {
                    imgWidth = this.width;
                    imgHeight = this.height;
                    var canvas = document.createElement("canvas");
                    var ctx = canvas.getContext("2d");
                    if (Math.max(imgWidth, imgHeight) > w) {
                        if (imgWidth > imgHeight) {
                            canvas.width = w;
                            canvas.height = w * imgHeight / imgWidth;
                        } else {
                            canvas.height = w;
                            canvas.width = w * imgWidth / imgHeight;
                        }
                    } else {
                        canvas.width = imgWidth;
                        canvas.height = imgHeight;
                        quality = 0.6;
                    }
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
                    var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
                    // 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间，请加以下语句，quality初始值根据情况自定
                    // while (base64.length / 1024 > 150) {
                    // 	quality -= 0.01;
                    // 	base64 = canvas.toDataURL("image/jpeg", quality);
                    // }
                    // 防止最后一次压缩低于最低尺寸，只要quality递减合理，无需考虑
                    // while (base64.length / 1024 < 50) {
                    // 	quality += 0.001;
                    // 	base64 = canvas.toDataURL("image/jpeg", quality);
                    // }
                    callback(this.fujinImg);//必须通过回调函数返回，否则无法及时拿到该值
                }
            },
    //转换
    // dataURLtoFile(dataurl, filename) {
    //   console.log(11111);
    //   var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    //       bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    //   while(n--){
    //       u8arr[n] = bstr.charCodeAt(n);
    //   }
    //   var obj = new Blob ([u8arr], {type:mime});
    //   console.log("obj",obj);
    //    var fd = new FormData();
    //     fd.append("file", obj,"image.png");
    //     console.log( fd.append("file", obj,"image.png"))  // 如果还需要传替他参数的话);
    //   console.log(new File([u8arr], filename, {type:mime}));
    //   $.ajax
    //   return new File([u8arr], filename, {type:mime});
      
    // },
    //重置表单
    resetForm(formName) {
      // this.$refs[formName].resetFields();
      this.username = "";
      this.user_code = "";
      this.minzu = "";
      this.age = "";
      this.radio3 = "";
      this.value1 = "";
      this.radio1 = "";
      this.mobile = "";
      this.learn_level = "";
      this.radio2 = "";
      this.job_to = "";
      this.sfzpic = "";
    },
    // base64转文件
    // dataURLtoFile(dataurl, filename) {
    //   var arr = dataurl.split(",");
    //   var mime = arr[0].match(/:(.*?);/)[1];
    //   var bstr = atob(arr[1]);
    //   var n = bstr.length;
    //   var u8arr = new Uint8Array(n);
    //   while (n--) {
    //     u8arr[n] = bstr.charCodeAt(n);
    //   }
    //   return new File([u8arr], filename, { type: mime });
    // },
    // 关闭摄像头
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
    },
  },
  // 重置表单
  reset() {},
};
</script>

<style lang="less" scope>
.abcimg{
  height: 440px;
  width: 340px;
}
.el-col-24 {
  width: 80%;
}
.entryFrom {
  display: flex;
  margin: 0 auto;
  .el-form {
    width: 90%;

    min-width: 500px;
    // text-align: center;
    .el-row {
      margin: 16px 0;
      .el-col {
        padding: 0;
      }
    }
  }
}
.el-form-item__content {
  widows: 100%;
}
.img {
  text-align: center;
}
.titlep {
  text-align: center;
}
.mb8 {
  width: 80%;
  text-align: center;
}
.el-form-item {
  margin-bottom: 0;
}
.radio {
  text-align: left;
}
.el-input {
  width: 200px;
  text-align: left;
}

.select {
  width: 100%;
}
.camera_outer {
  position: relative;
  overflow: hidden;
  background-size: 100%;
  margin-top: 20px;
  // width: 80%;
  video,
  canvas,
  .tx_img {
    -moz-transform: scaleX(-1);
    -webkit-transform: scaleX(-1);
    -o-transform: scaleX(-1);
    transform: scaleX(-1);
  }
  .btn_camera {
    position: absolute;
    bottom: 4px;
    left: 0;
    right: 0;
    height: 50px;
    background-color: rgba(0, 0, 0, 0.3);
    line-height: 50px;
    text-align: center;
    color: #ffffff;
  }
  .bg_r_img {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 0;
  }
  .img_bg_camera {
    position: absolute;
    right: 30px;
    top: 0;
    img {
      width: 150px;
      height: 150px;
    }
    .img_btn_camera {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 50px;
      line-height: 50px;
      text-align: center;
      background-color: rgba(0, 0, 0, 0.3);
      color: #ffffff;
      .loding_img {
        width: 50px;
        height: 50px;
      }
    }
  }
}
.IMg {
  text-align: center;
}
.vdeo {
  width: 50%;
  margin: 0 auto;
}
</style>